library(RSNNS)

# function compute accuracy
# input: 
#	model: list(weights, bias)
#	x: a n*d matrix in which each row is a datum point
#	y: a n*1 matrix in which each row is the target of x[i,]
# output: classification error
compute.accuracy <- function(model, x, y) {
	n.cases <- dim(x)[1]
	pred <- (predict(model, x) > 0.5) * 1.
	acc	<- sum((y == pred)*1.)/n.cases
	return(acc)
}

# function compute error
# input: 
#	x: a n*d matrix in which each row is a datum point
#	y: a n*1 matrix in which each row is the target of x[i,]
#	ratio: n_train / n_test
# output: list(x.train, y.train, x.test, y.test)
split.data <- function(x, y, ratio) {
	ncases <- dim(x)[1]
	ntrain <- round(ncases * ratio / (ratio+1))
	list(
		x.train = x[1:ntrain,],
		y.train = as.matrix(y[1:ntrain,]),
		x.test = x[(ntrain+1):ncases,],
		y.test = as.matrix(y[(ntrain+1):ncases,]))
}


############################################################

	maxit <- 100
	learn.rate <- 0.1
	size = c(5)

	# load data from the file 'breast-cancer.dat.shuf'
	dat <- read.table("breast-cancer.dat.shuf") 
	in.dim <- dim(dat)[2] - 1

	x <- as.matrix(dat[,2:in.dim+1]) 
	x <- normalizeData(x)
	y <- as.matrix((dat[,1] == dat[1,1]) * 1)

	# split the dataset
	splitdat <- split.data(x, y, 10)

	# train a perceptron
	model <- mlp(splitdat$x.train, splitdat$y.train, 
				maxit = maxit, size = size, learnFuncParams = learn.rate)

	# report result
	plotIterativeError(model)
	cat("accuracy: ", compute.accuracy(model, splitdat$x.test, splitdat$y.test), "\n")

